import less from 'less';

export const cacheObj = (key: string): { set(obj: any): void; get(): any } => {
  return {
    set(obj) {
      localStorage.setItem(key, obj && JSON.stringify({ [key]: obj }));
    },
    get() {
      const str = localStorage.getItem(key);
      return str && JSON.parse(str)[key];
    },
  };
};

export const cacheStr = (key: string) => {
  return {
    set(str: string) {
      localStorage.setItem(key, str);
    },
    get() {
      return localStorage.getItem(key);
    },
  };
};

// 最快应多少毫秒后发生
export const emitAfterMS = (ms: number): (() => Promise<boolean>) => {
  const timer = undefined;
  return () => {
    return new Promise((resolve, reject) => {
      if (timer) {
        clearTimeout(timer);
        reject('claer timer');
      }
      setTimeout(() => {
        resolve(true);
      }, ms);
    });
  };
};

const emitAfter1000ms = emitAfterMS(1000);
export function renderCssAfter1000ms(cssStr: string, root: string): Promise<string> {
  return emitAfter1000ms().then((value: boolean) => {
    if (value) {
      return renderCss(cssStr, root);
    } else {
      return '';
    }
  });
}

export function renderCss(cssStr: string, root: string): Promise<string> {
  const str = root ? `${root}{${cssStr}}` : cssStr;
  return less.render(str).then(
    output => {
      return Promise.resolve(`<style>${output.css}</style>`);
    },
    () => {
      return Promise.resolve('');
    },
  );
}
